import { defineEventHandler, readBody } from 'h3';

import { usePageResponseSuccess, useResponseError } from '../utils/response';

// 生成维保审批数据的辅助函数
function generateMaintenanceAuditData() {
  const auditData = [];
  const baseRequestId = 50_001;

  // 模拟车辆和司机数据（符合7位车牌格式）
  const vehicles = [
    { vehicleId: 30_001, licensePlate: '京A12345' },
    { vehicleId: 30_002, licensePlate: '京B56789' },
    { vehicleId: 30_003, licensePlate: '京C90123' },
    { vehicleId: 30_004, licensePlate: '京D34567' },
    { vehicleId: 30_005, licensePlate: '京E78901' },
    { vehicleId: 30_006, licensePlate: '京F12345' },
    { vehicleId: 30_007, licensePlate: '京G56789' },
    { vehicleId: 30_008, licensePlate: '京H90123' },
    { vehicleId: 30_009, licensePlate: '京J34567' },
    { vehicleId: 30_010, licensePlate: '京K78901' },
  ];

  const drivers = [
    { driverId: 10_001, driverName: '张三' },
    { driverId: 10_002, driverName: '李四' },
    { driverId: 10_003, driverName: '王五' },
    { driverId: 10_004, driverName: '赵六' },
    { driverId: 10_005, driverName: '孙七' },
    { driverId: 10_006, driverName: '周八' },
    { driverId: 10_007, driverName: '吴九' },
    { driverId: 10_008, driverName: '郑一' },
    { driverId: 10_009, driverName: '王二' },
    { driverId: 10_010, driverName: '陈三' },
  ];

  // 故障描述模板
  const descriptions = [
    '发动机异响，需要检查',
    '常规保养，更换机油',
    '刹车系统检查',
    '轮胎更换',
    '空调系统维修',
    '变速箱油更换',
    '电瓶更换',
    '四轮定位',
    '雨刷更换',
    '全车检查',
    '机油滤清器更换',
    '火花塞更换',
    '刹车片更换',
    '轮胎动平衡',
    '空调滤清器更换',
    '燃油系统清洗',
    '节气门清洗',
    '冷却系统检查',
    '电瓶检测',
    '灯光系统检查',
  ];

  for (let i = 0; i < 30; i++) {
    const vehicle = vehicles[i % vehicles.length];
    const driver = drivers[i % drivers.length];
    const requestType = i % 2 === 0 ? '维修' : '保养';
    const description = descriptions[i % descriptions.length];

    // 生成随机的申请时间（近6个月）
    const year = 2024;
    const month = Math.floor(Math.random() * 6) + 1;
    const day = Math.floor(Math.random() * 28) + 1;
    const hour = Math.floor(Math.random() * 24);
    const minute = Math.floor(Math.random() * 60);
    const applyTime = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')} ${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;

    // 生成图片URL（至少1条有图，1条无图）
    const images = [];
    if (i % 3 === 0) {
      images.push(`/mock/images/car${i + 1}.jpg`);
    }

    auditData.push({
      request_id: baseRequestId + i,
      vehicle_id: vehicle.vehicleId,
      license_plate: vehicle.licensePlate,
      driver_id: driver.driverId,
      driver_name: driver.driverName,
      request_type: requestType,
      description,
      images,
      apply_time: applyTime,
    });
  }

  return auditData;
}

// 维保审批数据模拟
const maintenanceAuditData = generateMaintenanceAuditData();

// 获取维保审批列表
export const getMaintenanceAuditHandler = defineEventHandler(async (event) => {
  try {
    const query = event.context.params || {};
    const page = Number.parseInt(query.page as string) || 1;
    const pageSize = Number.parseInt(query.pageSize as string) || 20;
    const licensePlate = query.licensePlate as string;
    const driverName = query.driverName as string;
    const requestType = query.requestType as string;

    // 筛选数据
    let filteredData = maintenanceAuditData;

    if (licensePlate) {
      filteredData = filteredData.filter((item) =>
        item.license_plate.includes(licensePlate),
      );
    }

    if (driverName) {
      filteredData = filteredData.filter((item) =>
        item.driver_name.includes(driverName),
      );
    }

    if (requestType) {
      filteredData = filteredData.filter(
        (item) => item.request_type === requestType,
      );
    }

    // 分页处理
    const total = filteredData.length;
    const startIndex = (page - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    const paginatedData = filteredData.slice(startIndex, endIndex);

    return usePageResponseSuccess(page, pageSize, paginatedData, {
      message: '获取成功',
    });
  } catch {
    return useResponseError('获取失败');
  }
});

// 提交维保审批
export const submitMaintenanceAuditHandler = defineEventHandler(
  async (event) => {
    try {
      const body = await readBody(event);
      const { vehicleId, driverId, requestType, description, images } = body;

      // 生成新的ID
      const newId =
        Math.max(...maintenanceAuditData.map((item) => item.request_id), 0) + 1;

      const newRecord = {
        request_id: newId,
        vehicle_id: vehicleId,
        driver_id: driverId,
        request_type: requestType,
        description,
        images: images || [],
        apply_time: new Date().toISOString().replace('T', ' ').slice(0, 19),
      };

      maintenanceAuditData.unshift(newRecord);

      return useResponseSuccess(newRecord);
    } catch {
      return useResponseError('提交失败');
    }
  },
);
